﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using Studio77.GuessTheWords2.Core;

namespace Studio77.GuessTheWords2.Utils
{
    public class AudioPlayHelper
    {
        static Popup popUp;
        private static MediaElement backgroundPlayer;

        static AudioPlayHelper()
        {
            popUp = new Popup();
            backgroundPlayer = new MediaElement();
            backgroundPlayer.Source = null;
            backgroundPlayer.MediaEnded += new RoutedEventHandler(backgroundPlayer_MediaEnded);
            popUp.Child = backgroundPlayer;
            popUp.IsOpen = true;
        }

        static void backgroundPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            if (backgroundPlayer.CurrentState != System.Windows.Media.MediaElementState.Opening)
            {
                if (StageManager.Instance.IsPlaySound)
                {
                    backgroundPlayer.Stop();
                    backgroundPlayer.Play();
                }
            }
        }

        public static void PlayBackground()
        {
            if (!StageManager.Instance.IsPlaySound)
            {
                return;
            }
            if (backgroundPlayer != null && backgroundPlayer.CurrentState == MediaElementState.Playing)
            {
                return;
            }
            try
            {
                StopBackground();

                backgroundPlayer.Source = new Uri("Sounds/background.mp3", UriKind.Relative);
                backgroundPlayer.Volume = 1;
                backgroundPlayer.AutoPlay = true;
                backgroundPlayer.Play();
            }
            catch (Exception)
            {
                backgroundPlayer.Source = null;
            }
        }

        public static void StopBackground()
        {
            if (backgroundPlayer != null && backgroundPlayer.CurrentState == MediaElementState.Playing)
            {
                try
                {
                    backgroundPlayer.Stop();
                }
                catch (Exception)
                {

                }
            }
        }
    }
}
